package user_m

import (
	"frozen-go-mini/common/domain"
	"frozen-go-mini/common/resource/mysql"
	"gorm.io/gorm"
)

type User struct {
	mysql.Entity
	ID     mysql.ID `gorm:"column:id"`
	Openid string   `gorm:"column:openid"` //  openid
	Avatar string   `gorm:"column:avatar"` //  头像
	Nick   string   `gorm:"column:nick"`   //  昵称
}

func (User) TableName() string {
	return "user"
}

// 根据获取/注册用户
func GetSetUserByOpenId(model *domain.Model, openid string) (User, error) {
	var user User
	if err := model.DB().Model(User{}).Where("openid = ?", openid).First(&user).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			return user, err
		} else {
			user.Openid = openid
			if err := model.DB().Create(&user).Error; err != nil {
				return user, err
			}
		}
	}
	return user, nil
}

func UpdateUserById(model *domain.Model, id mysql.ID, avatar, nick string) (User, error) {
	var user User
	updates := map[string]interface{}{}
	if len(avatar) > 0 {
		updates["avatar"] = avatar
	}
	if len(nick) > 0 {
		updates["nick"] = nick
	}
	if err := model.DB().Model(User{}).Where("id = ?", id).Updates(updates).Error; err != nil {
		return User{}, err
	}
	if err := model.DB().Model(User{}).Where("id = ?", id).First(&user).Error; err != nil {
		return User{}, err
	}
	return user, nil
}
